package online.shenme.itcast.service;



import online.shenme.itcast.dao.QuestionDao;
import online.shenme.itcast.dao.QuestionInfoDao;
import online.shenme.itcast.dao.UserDao;
import online.shenme.itcast.entity.ExamInfo;
import online.shenme.itcast.entity.Question;
import online.shenme.itcast.entity.QuestionInfo;
import online.shenme.itcast.entity.User;
import online.shenme.itcast.exception.*;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ExamServiceImpl
        implements ExamService, Serializable {
    private static final long serialVersionUID = -89697097419788051L;

    /**
     * 是否已经开始答题
     */
    private boolean started = false;
    /**
     * 是否已经答题结束
     */
    private boolean finish = false;

    @Override
    public User login(String id, String pwd) throws IOException {
        // 实现登录功能
        if (!id.matches("\\d+")) {
            throw new IDPatternException("ID必须为数字");
        }
        String regex = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W_]+$)(?![A-Za-z\\W_]+$)(?![A-Z0-9\\W_]+$)[\\w\\W]{6,}$";
        if (!pwd.matches(regex)) {
            throw new PWDPatternException("密码必须满足6位数,且包含大小字母、小写字母、数字和特殊符号!");
        }
        HashMap<String, User> users = new UserDao().AllUser();
        if (users == null) {
            throw new UserNullExpetion("服务器用户数据为空！");
        } else {
            if (!pwd.equals(users.get(id).getPwd()))
                throw new PWDNoMatchException("帐号密码不匹配！");
        }
        return users.get(id);
    }

    @Override
    public ExamInfo getExamInfo(User user) {
        String title = "JavaSE阶段性考试（一）";
        int timelimit = 1;
        int qustionCount = 20;
        return new ExamInfo(title, user, timelimit, qustionCount);
    }

    @Override
    public QuestionInfo getQustionInfo(int index) throws IOException {
        return QuestionInfoDao.getQuestionInfos().get(index);
    }

    @Override
    public void setQustionInfo(List<Integer> answer, int index) throws IOException {
        ArrayList<QuestionInfo> questionInfo = QuestionInfoDao.getQuestionInfos();
        questionInfo.get(index).setUserAnswers(answer);
    }

    @Override
    public QuestionInfo next(int index) throws IOException {
        return QuestionInfoDao.getQuestionInfos().get(index) ;
    }

    @Override
    public QuestionInfo prev(int index) throws IOException {
        return QuestionInfoDao.getQuestionInfos().get(index);
    }

    @Override
    public int userScore(ExamInfo examInfo) throws IOException {
        ArrayList<QuestionInfo> infos = QuestionInfoDao.getQuestionInfos();
        ArrayList<Question> questions = QuestionDao.AllQuestion();
        HashMap<String,Question> map=new HashMap<>();
        int sum=0;
        for (int i = 0; i < questions.size(); i++) {
            map.put(questions.get(i).getTitle(), questions.get(i));
        }
        for (QuestionInfo info : infos) {
            String title = info.getQuestion().getTitle();
            if (map.containsKey(title)){
                List<Integer> userAnswers = info.getUserAnswers();
                List<Integer> answer = map.get(title).getAnswer();
                if (userAnswers.equals(answer)) sum+=map.get(title).getScore();
            }
        }
        BufferedWriter writer = new BufferedWriter(new FileWriter("project/src/online/shenme/itcast/file/score.txt",true));
        writer.write("考生ID:"+examInfo.getUser().getId()+"\t考试分数为:"+sum);
        writer.newLine();
        writer.close();
        return sum;
    }

    @Override
    public long updateTime(ExamInfo examInfo) {
      return (long) examInfo.getTimeLimit() *60*1000;
    }

    @Override
    public void isExam(User user) throws IOException {
        BufferedReader bw = new BufferedReader(new FileReader("project/src/online/shenme/itcast/file/score.txt"));
        String s;String id = null;
        while ((s = bw.readLine()) != null) {
            String[] split = s.split("\t");
             id = split[0].split(":")[1];
        }
        if (user.getId().equals(id)){
            throw new UserReExamException("已参加考试!");
        }
    }

    @Override
    public int queryScore(User user) throws IOException {
        BufferedReader bw = new BufferedReader(new FileReader("project/src/online/shenme/itcast/file/score.txt"));
        String s;
        while ((s = bw.readLine()) != null) {
            String[] split = s.split("\t");
             return Integer.parseInt(split[1].split(":")[1]);
        }
        return -1;
    }
}